<?php
/**
 * Create By: PhpStorm
 * User: yihua
 * File: GetUserCurrency.php
 * Date: 2017/1/25
 * Time: 2:06
 */
namespace app\api\model\page\user;

use app\api\model\dao\UserCurrency;
use app\library\Error;
use app\library\PageBase;


class GetUserCurrency extends PageBase
{
    private $objCurrency;

    public function __construct()
    {
        parent::__construct();
        $this->objCurrency = new UserCurrency();
    }

    public function excute($param)
    {
        $ret = $this->check($param);
        if (true !== $ret) {
            return $this->getRes(Error::ERR_PARAM, $ret);
        }
        unset($ret);
        $type = $param['type'];
        $ret = $this->objCurrency->getCurrencyByUserid($param['user_id'], $type);
        if (false === $ret) {
            return $this->getRes(Error::ERR_SYS);
        }
        if (count($ret)) {
            $data = $ret->toArray();
        } else {
            $data = $this->zeroCount($param['user_id'], $type);
        }
        $this->data = $data;
        if (false === $ret) {
            return $this->getRes(Error::ERR_SYS);
        }

        return $this->getRes();

    }


    public function check($param)
    {
        $rule = [
            'user_id' => 'require',
            'type' => 'require|In:1,2',
        ];
        $msg = [
            'user_id.require' => 'user_id必须',
            'type.require' => 'type必须',
            'type.In' => '类型错误',
        ];
        $validate = new \think\Validate($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            return $validate->getError();
        }
        return $result;
    }

    public function zeroCount($user_id, $type)
    {
        return [
            'user_id' => (int)$user_id,
            'currency_type' => (int)$type,
            'amount' => 0
        ];
    }
}